package com.jiantong.user.impl.service;

import com.google.common.base.Throwables;
import com.jiantong.user.impl.dao.UserRoleDao;
import com.jiantong.user.model.UserRole;
import com.jiantong.user.service.UserRoleReadService;
import com.jiantong.user.service.UserRoleWriteService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * Created by niufei on 2017/4/5.
 */
@Slf4j
@Service
@RpcProvider
public class UserRoleWriteServiceImpl implements UserRoleWriteService {

    private final UserRoleDao userRoleDao;

    @Autowired
    public UserRoleWriteServiceImpl(UserRoleDao userRoleDao) {
        this.userRoleDao = userRoleDao;
    }
    @Override
    public Response<Long> create(UserRole userRole){
        try {
            userRoleDao.create(userRole);
            return Response.ok(userRole.getId());
        } catch (DuplicateKeyException e) {
            log.error("failed to create {}, cause:{}", Throwables.getStackTraceAsString(e));
            return Response.fail("user.loginId.duplicate");
        } catch (Exception e) {
            log.error("failed to create {}, cause:{}", Throwables.getStackTraceAsString(e));
            return Response.fail("user.create.fail");
        }
    }

    @Override
    public Response<Boolean> update(UserRole userRole) {
        try {
        return Response.ok(userRoleDao.update(userRole));
        } catch (DuplicateKeyException e) {
            log.error("failed to create {}, cause:{}", Throwables.getStackTraceAsString(e));
            return Response.fail("user.loginId.duplicate");
        } catch (Exception e) {
            log.error("failed to create {}, cause:{}", Throwables.getStackTraceAsString(e));
            return Response.fail("user.create.fail");
        }
    }


}
